package com.oceansoft.mobile.biz.admin.controller;

import static com.oceansoft.mobile.common.Constant.BIZ_FILE_PATH_PREFIX;
import static com.oceansoft.mobile.common.Constant.PIC_ART_PATH;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.coobird.thumbnailator.Thumbnails;
import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.oceansoft.mobile.biz.admin.entity.BasesiteArticlePic;
import com.oceansoft.mobile.biz.admin.entity.Merchant;
import com.oceansoft.mobile.biz.admin.entity.SysUser;
import com.oceansoft.mobile.biz.admin.service.IBaseSiteAttachmentService;
import com.oceansoft.mobile.biz.admin.service.IMerchantService;
import com.oceansoft.mobile.common.Constant;
import com.oceansoft.mobile.common.base.entity.Result;

/**
 * 文件上传下载控制器
 *
 * @author: qiur
 */
@Controller
@RequestMapping("basesite/file")
public class BaseSiteUploadController {

    @Resource
    private IBaseSiteAttachmentService attachmentService;
    @Resource
    private IMerchantService merchantService;


    /**
     * 上传封面图片
     *
     * @param merchantId 商家编号
     * @param request    MultipartHttpServletRequest
     * @return Result
     */
    @RequestMapping(value = "upload/{merchant_id}", method = RequestMethod.POST)
    @ResponseBody
    public Result upload(@PathVariable("merchant_id") long merchantId, MultipartHttpServletRequest request) {
        List<BasesiteArticlePic> files = new ArrayList<BasesiteArticlePic>();
        Iterator<String> itr = request.getFileNames();
        String productId = request.getParameter("sid");
        Merchant mer=merchantService.loadMerchantBySid(merchantId);
        while (itr.hasNext()) {
        	String _root =Constant.PIC_BASE_PATH;//request.getSession().getServletContext().getRealPath("/");
            /*String _root = request.getServletContext().getRealPath("/");*/
            MultipartFile mpf = request.getFile(itr.next());
            //文件信息解析
            BasesiteArticlePic productPic = new BasesiteArticlePic();
            productPic.setProductId(Long.valueOf(productId));
            String _orig_name = mpf.getOriginalFilename();
            int _last_dot_pos = _orig_name.lastIndexOf(".");
            productPic.setOriginalName(_orig_name);
            productPic.setFileSize(mpf.getSize() / 1024);
            productPic.setFileType(mpf.getContentType());
            productPic.setFileName(_orig_name);
            if (-1 != _last_dot_pos) {
                productPic.setSuffix(_orig_name.substring(_last_dot_pos));
            }
            try {
                productPic.setBytes(mpf.getBytes());
                fileProcessor(mer.getCompany_name(), _root, merchantId, productPic);
                //保存数据库，保存成功后将文件写入文件系统
                long pk = attachmentService.savePic(productPic);
                if (pk > 0) {
                    productPic.setId(pk);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            files.add(productPic);
        }
        return new Result(files);
    }
    /**
     * 上传文章图片文件
     *
     * @param merchantId 商家编号
     * @param request    MultipartHttpServletRequest
     * @return Result
     */
    @RequestMapping(value = "uploadNicedit/{merchant_id}", method = RequestMethod.POST)
    @ResponseBody
    public Result uploadNicedit(@PathVariable("merchant_id") long merchantId, MultipartHttpServletRequest request, HttpServletResponse response) {
    	List<BasesiteArticlePic> files = new ArrayList<BasesiteArticlePic>();
    	Iterator<String> itr = request.getFileNames();
    	Merchant mer=merchantService.loadMerchantBySid(merchantId);
    	while (itr.hasNext()) {
    		String _root =Constant.PIC_BASE_PATH;//request.getSession().getServletContext().getRealPath("/");
    		MultipartFile mpf = request.getFile(itr.next());
    		//文件信息解析
    		BasesiteArticlePic productPic = new BasesiteArticlePic();
    		String _orig_name = mpf.getOriginalFilename();
    		int _last_dot_pos = _orig_name.lastIndexOf(".");
    		productPic.setOriginalName(_orig_name);
    		productPic.setFileSize(mpf.getSize() / 1024);
    		productPic.setFileType(mpf.getContentType());
    		productPic.setFileName(_orig_name);
    		if (-1 != _last_dot_pos) {
    			productPic.setSuffix(_orig_name.substring(_last_dot_pos));
    		}
    		
    		PrintWriter out = null;
    		try {
    			productPic.setBytes(mpf.getBytes());
    			String newFileName=fileProcessor(_root, merchantId, productPic);
    			out = response.getWriter();
    			StringBuilder baseP=new StringBuilder().append(request.getScheme()).append("://").append(request.getServerName()).append(":").append(request.getServerPort()).append("/").append(merchantId).append("/").append(Constant.PIC_ART_PATH).append("/");
    			JSONObject json_object = new JSONObject();
    			json_object.put("done",0);
    			json_object.put("url",baseP.toString()+newFileName);
    			json_object.put("width",120);
    			out.print(json_object.toString());
    		} catch (IOException e) {
    			e.printStackTrace();
    		}finally{
    			if(out!=null) {
    				out.close();  
    				out = null;
    			}
    		}
    		files.add(productPic);
    	}
    	return new Result(files);
    }

    /**
     * 上传图片文件
     *
     * @param request MultipartHttpServletRequest
     * @return Result
     */
    @RequestMapping(value = "logo/upload", method = RequestMethod.POST)
    @ResponseBody
    public Result uploadSiteLogo(MultipartHttpServletRequest request) {
    	SysUser merchant = ((SysUser) request.getSession().getAttribute(Constant.GLOBAL_SESSION));
        List<BasesiteArticlePic> files = new ArrayList<BasesiteArticlePic>();
        Iterator<String> itr = request.getFileNames();
        while (itr.hasNext()) {
        	String _root = Constant.PIC_BASE_PATH;
            MultipartFile mpf = request.getFile(itr.next());
            //文件信息解析
            BasesiteArticlePic productPic = new BasesiteArticlePic();
            String _orig_name = mpf.getOriginalFilename();
            int _last_dot_pos = _orig_name.lastIndexOf(".");
            productPic.setOriginalName(_orig_name);
            productPic.setFileSize(mpf.getSize() / 1024);
            productPic.setFileType(mpf.getContentType());
            productPic.setFileName(_orig_name);
            if (-1 != _last_dot_pos) {
                productPic.setSuffix(_orig_name.substring(_last_dot_pos));
            }
            try {
                productPic.setBytes(mpf.getBytes());
                fileProcessor(_root, merchant.getMerchant_id(), productPic);
            } catch (IOException e) {
                e.printStackTrace();
            }
            files.add(productPic);
        }
        return new Result(files);
    }

    /**
     * 删除已上传图片（同时删除文件）
     *
     * @param id 图片ID
     * @return Result
     */
    @ResponseBody
    @RequestMapping(value = "{attach_id}", method = RequestMethod.DELETE)
    public Result deletePicsById(HttpServletRequest request, @PathVariable("attach_id") long id) {
        return attachmentService.deletePicById(Constant.PIC_BASE_PATH, id);
    }

    /**
     * 文件处理
     *
     * @param root          系统根目录
     * @param merchantId    商家ID
     * @param watermarkText 水印文字名称
     * @param productPic    文件数据对象
     * @throws IOException
     */
    private String fileProcessor(String root, long merchantId, BasesiteArticlePic productPic) throws IOException {
        //重新生成文件名
        String _name = UUID.randomUUID().toString().replaceAll("-", "");
        //获取磁盘文件绝对路径
        String _biz_path = String.format("%1$s%6$s%2$s%6$s%3$s%6$s%4$s%5$s", BIZ_FILE_PATH_PREFIX.replace('/', File.separatorChar), merchantId,PIC_ART_PATH, _name, productPic.getSuffix(), File.separator);
        productPic.setFileName(_name + productPic.getSuffix());
        productPic.setUrl(_biz_path);
        String _temp_path = String.format("%1$s%2$s", root, productPic.getUrl());
        File _temp_file = File.createTempFile(_name, productPic.getSuffix());
        FileUtils.writeByteArrayToFile(_temp_file, productPic.getBytes());
      //图片压缩
		Thumbnails.of(_temp_file).size(300, 600).toFile(new File(_temp_path));
		_temp_file.delete();
        return _name+productPic.getSuffix();
      
    }
    /**
     * 文件处理
     *
     * @param root          系统根目录
     * @param merchantId    商家ID
     * @param watermarkText 水印文字名称
     * @param productPic    文件数据对象
     * @throws IOException
     */
    private String fileProcessor(String watermarkText, String root, long merchantId, BasesiteArticlePic productPic) throws IOException {
    	//重新生成文件名
    	String _name = UUID.randomUUID().toString().replaceAll("-", "");
    	//获取磁盘文件绝对路径
    	String _biz_path = String.format("%1$s%5$s%2$s%5$s%3$s%4$s", BIZ_FILE_PATH_PREFIX.replace('/', File.separatorChar), merchantId, _name, productPic.getSuffix(), File.separator);
    	productPic.setFileName(_name + productPic.getSuffix());
    	productPic.setUrl(_biz_path);
    	//将文件上传至当前用户业务目录 /WebRoot/static/biz/{merchant_id}/header.png
    	String _temp_path = String.format("%1$s%2$s", root, productPic.getUrl());
    	File _temp_file = File.createTempFile(_name, productPic.getSuffix());
    	FileUtils.writeByteArrayToFile(_temp_file, productPic.getBytes());
    	
    	//图片压缩
		Thumbnails.of(_temp_file).size(300, 600).toFile(new File(_temp_path));
		_temp_file.delete();
    	return _name;
    	
    }

    /**
     * 生成水印图片
     *
     * @param text            String 文字
     * @param alignType       文字位置（left,right,center）
     * @param y_pos           y坐标
     * @param backgroundColor Color 背景色
     * @param fontColor       Color 字色
     * @param font            Font 字体字形字号
     * @return true生成成功 false生成失败
     */
    private static boolean genWatermarkImage(String watermarkPath, String text, String alignType, int y_pos, Color backgroundColor, Color fontColor, Font font) {
        try {
            //文字大小设置
            int size = font.getSize();
            //水印尺寸
            int width = text.length() * 22 + 5;
            int height = (int) (size * 1.2);
            // 创建BufferedImage对象
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            // 获取Graphics2D
            Graphics2D g2d = image.createGraphics();
            // ----------  增加下面的代码使得背景透明  -----------------
            image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
            g2d.dispose();
            g2d = image.createGraphics();
            // ----------  背景透明代码结束  -----------------
            // 画图
            g2d.setColor(new Color(0, 0, 0));
            g2d.setStroke(new BasicStroke(1));
            g2d.fillRect(0, 0, width, height);//绘制矩形
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // 去除锯齿(当设置的字体过大的时候,会出现锯齿)
            //绘制文字
            g2d.setColor(fontColor);
            g2d.setFont(font);
            g2d.drawString(text, 5, size);
            //释放对象
            g2d.dispose();
            // 保存文件
            ImageIO.write(image, "png", new File(watermarkPath));
        } catch (Exception e) {
            System.out.println("create watermark file failure!");
            e.printStackTrace();
            return false;
        }
        return true;
    }
    public boolean isexitsPath(String filePath){
    	String paths[] = filePath.split("\\\\");
        String dir = paths[0];
        for (int i = 0; i < paths.length - 2; i++) {
            try {
                dir = dir + "/" + paths[i + 1];
                File dirFile = new File(dir);
                if (!dirFile.exists()) {
                    dirFile.mkdir();
                    System.out.println("创建目录为：" + dir);
                }
            } catch (Exception err) {
                System.err.println("ELS - Chart : 文件夹创建发生异常");
            }
        }
        File fp = new File(filePath);
        if(!fp.exists()){
            return true; // 文件不存在，执行下载功能
        }else{
            return false; // 文件存在不做处理
        }
    }
   
}
